﻿using Microsoft.WindowsAzure.MobileServices;
using SQLite;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TestMatrix.BLController;
using TestMatrix.DataModel;
using TestMatrix.Model;

namespace TestMatrix.Phone
{
    public class ETLHelper
    {
        public static void InsertLocalLastUpdateDT(string table, DateTime dt)
        {
            SQLiteConnection conn = DBHelper.getConnection();

            string tick = dt.Ticks.ToString();

            tblETLHistory row = new tblETLHistory()
            {
                TableName = table,
                LastUpdateDT = tick
            };

            conn.Insert(row);
        }

        public static DateTime GetLocalLastUpdateDT(string table)
        {
            SQLiteConnection conn = DBHelper.getConnection();
            conn.CreateTable<tblETLHistory>();

            List<tblETLHistory> rows = conn.Table<tblETLHistory>().Where(r=>r.TableName==table).OrderByDescending(x => x.ID).Take(1).ToList();

            DateTime result = new DateTime(0, DateTimeKind.Utc);

            if (rows.Count == 1)
            {
                long tick = Convert.ToInt64(rows[0].LastUpdateDT);
                result = new DateTime(tick, DateTimeKind.Utc);
            }

            return result;
        }

        public async static Task<DateTime> GetAzureLastUpdateDT(string table, DateTime clientDT)
        {
            IMobileServiceTable<ETLHistoryAzure> azureETLHistory = App.MobileService.GetTable<ETLHistoryAzure>();
            
            IMobileServiceTableQuery<ETLHistoryAzure> query = azureETLHistory.Where(r => r.TableName == table && r.LastUpdateDT > clientDT).OrderBy(r => r.Id).Take(1);

            List<ETLHistoryAzure> rows = await query.ToListAsync();

            DateTime result = new DateTime(9999, 1, 1).ToUniversalTime();

            if (rows.Count == 1)
                result = rows[0].LastUpdateDT.ToUniversalTime();

            return result;
        }
    }
}
